package com.googlecode.q2xml.main;

import java.io.File;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.googlecode.q2xml.service.IndexerService;
import com.googlecode.q2xml.service.IndexerServiceImpl;
import com.googlecode.q2xml.service.proxy.DAOProxy;

/**
 * to run this.. the sql squery should exist in a file named `in.txt` in the classpath of this project
 * 
 * @author mohammad_abdullah
 *
 */
public class Main
{
	public static void main(String[] args) throws Exception
	{
		IndexerService service = (IndexerService) DAOProxy.newInstance(new IndexerServiceImpl());
		List result = service.getSearchResult();
		if (result.size() > 0)
		{
			Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
			Element rootElement = doc.createElement("root");
			doc.appendChild(rootElement);
			for (Object object : result)
			{
				Element objectElement = doc.createElement(object.getClass().getSimpleName());
				rootElement.appendChild(objectElement);
				Field[] fields = object.getClass().getFields();
				for (Field field : fields)
				{
					Element element = doc.createElement(field.getName());
					element.appendChild(doc.createTextNode(field.get(object) == null ? "" : field.get(object).toString()));
					objectElement.appendChild(element);
				}
			}

			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(doc);
			StreamResult ret = new StreamResult(new PrintWriter(new File("out.txt")));
			transformer.transform(source, ret);

		}
	}

}
